package com.elvin.zoe.parser.im;

import java.util.ArrayList;
import java.util.List;

import com.elvin.zoe.pojo.Message;

public class MsnParser extends ImParser {

    @Override
    protected List<String> getMessageTokens(String originalHtml) {
        String messageStartToken = "<Message";
        String messageEndToken = "</Message>";
        List<String> messageTokens = new ArrayList<String>();
        int tokenStart = originalHtml.indexOf(messageStartToken);
        while (tokenStart > 0) {
            int tokenEnd = originalHtml.indexOf(messageEndToken, tokenStart) + messageEndToken.length();
            messageTokens.add(originalHtml.substring(tokenStart, tokenEnd));
            tokenStart = originalHtml.indexOf(messageStartToken, tokenEnd);
        }
        return messageTokens;
    }

    @Override
    protected int getMessageType(String messageToken) {
        String refined = messageToken.replace("\n", "").replace(".", " ").toLowerCase();
        if(refined.indexOf("<From><User FriendlyName=\"Elvin".toLowerCase()) > 0)
            return Message.OUTGOING;
        else
            return Message.INCOMMING;
    }

    @Override
    protected String getMessageDatetime(String messageToken) {
        String startToken = "DateTime=\"";
        int tokenStart = messageToken.indexOf(startToken) + startToken.length();
        int tokenEnd = messageToken.indexOf("\"", tokenStart);

        String datetimeToken = messageToken.substring(tokenStart, tokenEnd).replace("Z", "+0000");
//        System.out.println("------------");
//        System.out.println(messageToken);
//        System.out.println(messageToken.substring(tokenStart, tokenEnd));
//        System.out.println(datetimeToken);
//        try {
//            System.out.println((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")).format((new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")).parse(datetimeToken)));
//        } catch (ParseException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }

        return datetimeToken;
    }

    @Override
    protected String getMessageDatetimeFormat() {
        return "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
    }

    @Override
    protected String getMessageText(String messageToken) {
        String refined = messageToken.replaceAll("<Text.*\">", "<Text>");
        String textStartToken = "<Text>";
        int tokenStart = refined.lastIndexOf(textStartToken) + textStartToken.length();
        int tokenEnd = refined.indexOf("</Text>", tokenStart);
        return refined.substring(tokenStart, tokenEnd);
    }


}
